Example A-3 : Program to Exercise gettimeofday()
#include <sys/time.h> #include <stdio.h> #define LOOPS 1000 /* * This function loops on gettimeofday() until the returned time * changes by more than 1 microsecond, then reports the difference. * * We look for a change of >1 usec because in some older systems * (apparently not in 6.2) IRIX, in order to ensure that gettimeofday() * never returns the same value twice while not actually updating the * timer, just adds 1 usec on each call until a normal dispatching * tick occurs. In 6.2 systems, IRIX actually recalculates the timer * on each call. * * The function also updates a maximum loop-count value. */ long getTODdiff(int * pMaxLoops) { long first, second; int nloops = 0; struct timeval tod; struct timezone tz; gettimeofday(&tod, &tz); first = tod.tv_usec; do { gettimeofday(&tod, &tz); second = tod.tv_usec; ++nloops; } while (first == (second-nloops)); if (first > second) second += 1000000; if (pMaxLoops) if (nloops > *pMaxLoops) *pMaxLoops = nloops; return second - first; } int main(int argc, char *argv[]) { int j, limit; int maxLoops = 0; long sample, sum, min, max; double mean; limit = LOOPS; if (argc > 1) limit = atoi(argv[1]); /* get past the first call, which is likely to be short */ sum = getTODdiff(NULL); /* exercise gettimeofday a few times */ for (j=0, sum=0, min=999999, max=0; j< limit; j++) { sample = getTODdiff(&maxLoops); sum += sample; if (sample > max) max = sample; if (sample < min) min = sample; } mean = sum/LOOPS; printf("gettimeofday() increments: min=%ld, mean=%g, max=%ld\n", min, mean, max); if (maxLoops > 1) printf("Max number of loops %d\n", maxLoops); else printf("Honest timer update in this system.\n"); return 0; }